﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace ImageServer
{
	/// <summary>
	/// Summary description for GetImage
	/// </summary>
	public class GetImage : IHttpHandler
	{

		public void ProcessRequest( HttpContext context )
		{
			#region Get Parameters

			string imgName = context.Request.QueryString[ "imagename" ];
			string altImgName = context.Request.QueryString[ "altimagename" ];

			//TODO: Some validation on the files so that hackers can't get access to any file on server :)

			string w = context.Request.QueryString[ "w" ];
			string h = context.Request.QueryString[ "h" ];

			#endregion

			#region Create ImageServer object and do some width or height checks

			ImageServer objImageServer = new ImageServer( imgName );
			if ( !String.IsNullOrEmpty( altImgName ) )
			{
				objImageServer = new ImageServer( imgName, altImgName );
			}

			if ( w != null && w.Length > 0 )
			{
				objImageServer.Width = int.Parse( w );
			}
			if ( h != null && h.Length > 0 )
			{
				objImageServer.Height = int.Parse( h );
			}

			#endregion

			#region Response the image or return 404 Not Found
			using ( System.Drawing.Image objImage = objImageServer.GetImage() )
			{
				context.Response.Cache.SetCacheability( HttpCacheability.Public );
				context.Response.Cache.SetLastModified( objImageServer.LastModifiedDateTime );
				context.Response.ContentType = "image/jpeg";
				if ( objImage == null )
				{
					context.Response.StatusCode = 404;
					context.Response.Status = "404 Not Found";
				}
				else
				{
					objImage.Save( context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg );
				}
				context.Response.End();
			}
			#endregion
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}